package com.chenqi.controller;

import com.chenqi.model.dto.LoginDTO;
import com.chenqi.model.dto.RegisterDTO;
import com.chenqi.model.entity.User;
import com.chenqi.service.UserService;
import com.chenqi.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @description: 用户控制层
 * @program: ardaicommunity
 * @author: ChenQi
 * @create: 2021-03-2021/3/8-08-58
 */

@RestController
@RequestMapping("/api/v1/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param registerDTO
     * @return
     */
    @PostMapping("/register")
    public JsonData register(@Valid @RequestBody RegisterDTO registerDTO) {
        int i = userService.registerUser(registerDTO);
        return i == 1 ? JsonData.BuildSuccess("注册成功!") : JsonData.BuildError("注册失败!");
    }

    /**
     * 登陆
     * @param loginDTO
     * @return
     */

    @PostMapping("/login")
    public JsonData login(@Valid @RequestBody LoginDTO loginDTO) {
        String token = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
        return token == null ? JsonData.BuildError("登陆失败") : JsonData.BuildSuccess(token, "登陆成功");
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    @GetMapping("/info")
    public JsonData info(HttpServletRequest request) {
        String username = (String) request.getAttribute("user_username");
        User userById = userService.findUserByUserName(username);
        return userById == null ? JsonData.BuildError("获取用户失败") : JsonData.BuildSuccess(userById, "获取用户成功!");
    }

    /**
     * 退出登陆
     * @return
     */
    @GetMapping("/logout")
    public  JsonData logout(){
        return JsonData.BuildSuccess("退出成功!");
    }

    /**
     * 获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/userInfoById/{id}")
    public JsonData userInfoById(@PathVariable("id") Integer id) {
        User userById = userService.findUserById(id);
        return userById == null ? JsonData.BuildError("查询失败") : JsonData.BuildSuccess(userById, "查询成功");
    }

    @PutMapping("/updateUser")
    public JsonData updateUser(@RequestBody User user) {
        int i = userService.updateUser(user);
        return i == 0 ? JsonData.BuildError("更新失败") : JsonData.BuildSuccess("更新成功");
    }
}
